package api

import (
	"encoding/json"
	"fmt"
	"github.com/jinzhu/copier"
	"github.com/labstack/echo/v4"
	"github.com/spf13/cast"
	global2 "longmen/server/config/global"
	"longmen/server/pkg/common/api_models"
	_const "longmen/server/pkg/common/helper/const"
	"longmen/server/pkg/common/helper/timehelper"
	"longmen/server/pkg/common/helper/util"
	"longmen/server/pkg/db/mysql/models/models_main"
	"longmen/server/pkg/db/redis/cache"
	"longmen/server/pkg/grpc_client"
	pb "longmen/server/pkg/protobuf"
	"time"
)

// @Summary 获取我的-私聊界面记录
// @Description 获取我的-私聊界面记录
// @Accept  json
// @Produce  json
// @Tags PirvateChat
// @Param   sendBody body api_models.GetPrivateChatRecordReq true "body"
// @Success 200 {object} api_models.GetPrivateChatRecordResp "result"
// @Router /api/privateChat/getRecord [POST]
func (base *Controller) GetPrivateChatRecord(c echo.Context) error {
	user, err := base.GetUserByCtx(c)
	if err != nil {
		user = &models_main.User{}
	}

	req := &api_models.GetPrivateChatRecordReq{}
	if err = util.Json2Struct(c.Get("body").(string), req); err != nil {
		return util.BuildFail(c, 1, "", err)
	}
	ctx, cancel := base.GrpcWithTimeout()
	defer cancel()
	resp, err := grpc_client.GrpcTencentImClient.GetPrivateChatRecord(ctx, &pb.PrivateChatRecordReq{
		UserId:   uint64(user.Id),
		Duration: uint32(req.Duration),
		DeviceId: req.DeviceId,
	})
	if err != nil {
		return util.BuildFail(c, 1, err.Error(), err)
	}
	res := api_models.GetPrivateChatRecordResp{}
	copier.Copy(&res, &resp)

	if user.Id <= 0 {
		user.Id = util.HashUid(req.DeviceId)
	}
	for _, v := range res.ChatsGroup {
		num := cache.GetPrivateChatUnread(v.AnchorId, user.Id)
		v.UnreadAnchor = api_models.UnreadAnchor{
			AnchorId:  v.AnchorId,
			UserId:    user.Id,
			UnreadNum: num,
		}
	}
	return util.BuildSuccess(c, res, "")
}

// @Summary 获取我的-私聊记录界面-详情
// @Description 获取我的-私聊记录界面-详情
// @Accept  json
// @Produce  json
// @Tags PirvateChat
// @Param   sendBody body api_models.GetPrivateChatRecordDetailReq true "body"
// @Success 200 {object} api_models.GetPrivateChatRecordDetailResp "result"
// @Router /api/privateChat/getRecordDetail [POST]
func (base *Controller) GetPrivateChatRecordDetail(c echo.Context) error {
	user, err := base.GetUserByCtx(c)
	if err != nil {
		user = &models_main.User{}
	}

	req := &api_models.GetPrivateChatRecordDetailReq{}
	if err = util.Json2Struct(c.Get("body").(string), req); err != nil {
		return util.BuildFail(c, 1, "", err)
	}
	ctx, cancel := base.GrpcWithTimeout()
	defer cancel()
	resp, err := grpc_client.GrpcTencentImClient.GetPrivateChatRecordDetail(ctx, &pb.PrivateChatRecordDetailReq{
		UserId:   uint64(user.Id),
		AnchorId: uint32(req.AnchorId),
		Duration: uint32(req.Duration),
		Page:     uint32(req.Page),
		Size:     uint32(req.Size),
		DeviceId: req.DeviceId,
	})
	if err != nil {
		return util.BuildFail(c, 1, err.Error(), err)
	}
	res := api_models.GetPrivateChatRecordDetailResp{}
	copier.Copy(&res, &resp)
	return util.BuildSuccess(c, res, "")
}

// @Summary 清空聊天记录
// @Description 清空聊天记录
// @Accept  json
// @Produce  json
// @Tags PirvateChat
// @Param   sendBody body api_models.DeletePrivateChatRecordReq true "body"
// @Success 200 {object} api_models.Response "result"
// @Router /api/privateChat/delRecord [POST]
func (base *Controller) DeletePrivateChatRecord(c echo.Context) error {
	user, err := base.GetUserByCtx(c)
	if err != nil {
		return util.BuildLoginTimeOut(c, err)
	}

	req := &api_models.DeletePrivateChatRecordReq{}
	if err = util.Json2Struct(c.Get("body").(string), req); err != nil {
		return util.BuildFail(c, 1, "", err)
	}
	ctx, cancel := base.GrpcWithTimeout()
	defer cancel()
	resp, err := grpc_client.GrpcTencentImClient.DeletePrivateChatRecord(ctx, &pb.DeletePrivateChatRecordReq{
		UserId:     uint32(user.Id),
		AnchorId:   uint32(req.AnchorId),
		DeviceInfo: base.GetDeviceInfo(c),
	})
	if err != nil {
		return util.BuildFail(c, 1, err.Error(), err)
	}
	return util.BuildSuccess(c, resp, "")
}

// @Summary 未读消息
// @Description 未读消息
// @Accept  json
// @Produce  json
// @Tags PirvateChat
// @Param   sendBody body api_models.UnReadMsgReq true "body"
// @Success 200 {object} api_models.UnReadMsgResp "result"
// @Router /api/privateChat/unreadMsg [POST]
func (base *Controller) UnreadMsg(c echo.Context) error {
	req := &api_models.UnReadMsgReq{}
	if err := util.Json2Struct(c.Get("body").(string), req); err != nil {
		return util.BuildFail(c, 1, "", err)
	}

	user, err := base.GetUserByCtx(c)
	if err != nil {
		user = &models_main.User{}
	}

	resp, err := base.Service.UnreadMsg(user, req)
	if err != nil {
		return util.BuildFail(c, 1, err.Error(), err)
	}
	return util.BuildSuccess(c, resp, "")
}

// @Summary 记录已读 （不用处理，getRecordDetail接口 已ReSetPrivateChatUnreadNum）
// @Description 记录已读
// @Accept  json
// @Produce  json
// @Tags PirvateChat
// @Param   sendBody body api_models.ReadRecordReq true "body"
// @Success 200 {object} api_models.Response "result"
// @Router /api/privateChat/read [POST]
func (base *Controller) ReadRecord(c echo.Context) error {
	req := &api_models.ReadRecordReq{}
	if err := util.Json2Struct(c.Get("body").(string), req); err != nil {
		return util.BuildFail(c, 1, "", err)
	}

	user, err := base.GetUserByCtx(c)
	if err != nil {
		user = &models_main.User{}
	}

	err = base.Service.ReadRecord(user, req)

	if err != nil {
		return util.BuildFail(c, 1, err.Error(), err)
	}
	return util.BuildSuccess(c, nil, "")
}

// @Summary 记录IM登陆
// @Description 记录IM登陆
// @Accept  json
// @Produce  json
// @Tags IM
// @Param   sendBody body api_models.ImLoginRecordReq true "body"
// @Success 200 {object} api_models.Response "result"
// @Router /api/imlogin/record [POST]
func (base *Controller) ImLoginRecord(c echo.Context) error {
	req := &api_models.ImLoginRecordReq{}
	if err := util.Json2Struct(c.Get("body").(string), req); err != nil {
		return util.BuildFail(c, 1, "", err)
	}
	req.Time = time.Now().Format(timehelper.TIME_LAYOUT_FORMAT_5)
	req.Platform = cast.ToInt(c.Request().Header.Get("platform"))

	b, _ := json.Marshal(req)
	//明细
	global2.GetRds().HSet(fmt.Sprintf(_const.IM_LOGIN_RECORD, time.Now().Format(timehelper.TIME_LAYOUT_FORMAT_4)), req.FromAccount, string(b))
	//去重统计
	global2.GetRds().SAdd(fmt.Sprintf(_const.IM_LOGIN_RECORD_SET, time.Now().Format(timehelper.TIME_LAYOUT_FORMAT_4)), req.FromAccount)
	//不去重统计
	global2.GetRds().Incr(fmt.Sprintf(_const.IM_LOGIN_RECORD_COUNT, time.Now().Format(timehelper.TIME_LAYOUT_FORMAT_4)))
	return util.BuildSuccess(c, nil, "")
}
